<!--
  应用表单组件
  @description SOP应用新增/编辑表单对话框
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('sop.app.appName')" prop="appName">
            <el-input
              v-model="formData.appName"
              :placeholder="t('sop.app.rules.appNameRequired')"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('sop.app.merchantNo')" prop="merchantNo">
            <el-select
              v-model="formData.merchantNo"
              :placeholder="t('sop.app.rules.merchantNoRequired')"
              style="width: 100%"
              filterable
              remote
              :remote-method="searchMerchants"
              :loading="merchantLoading"
            >
              <el-option
                v-for="merchant in merchantOptions"
                :key="merchant.merchantNo"
                :label="`${merchant.merchantNo} - ${merchant.merchantName}`"
                :value="merchant.merchantNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('sop.app.rateLimitPerSecond')" prop="rateLimitPerSecond">
            <el-input-number
              v-model="formData.rateLimitPerSecond"
              :placeholder="t('sop.app.rules.rateLimitPerSecondRequired')"
              :min="1"
              :max="1000"
              style="width: 100%"
            />
            <div class="form-tip">{{ t('sop.app.rateLimitPerSecondTip') }}</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('sop.app.rateLimitPerMinute')" prop="rateLimitPerMinute">
            <el-input-number
              v-model="formData.rateLimitPerMinute"
              :placeholder="t('sop.app.rules.rateLimitPerMinuteRequired')"
              :min="1"
              :max="10000"
              style="width: 100%"
            />
            <div class="form-tip">{{ t('sop.app.rateLimitPerMinuteTip') }}</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="t('sop.app.ipWhitelist')" prop="ipWhitelist">
        <el-input
          v-model="formData.ipWhitelist"
          type="textarea"
          :placeholder="t('sop.app.rules.ipWhitelistPlaceholder')"
          :rows="3"
          maxlength="1000"
          show-word-limit
        />
        <div class="form-tip">{{ t('sop.app.ipWhitelistTip') }}</div>
      </el-form-item>

      <el-form-item :label="t('sop.app.notifyUrl')" prop="notifyUrl">
        <el-input
          v-model="formData.notifyUrl"
          :placeholder="t('sop.app.rules.notifyUrlPlaceholder')"
          maxlength="500"
        />
        <div class="form-tip">{{ t('sop.app.notifyUrlTip') }}</div>
      </el-form-item>

      <el-form-item :label="t('sop.app.webhookSecret')" prop="webhookSecret">
        <el-input
          v-model="formData.webhookSecret"
          :placeholder="t('sop.app.rules.webhookSecretPlaceholder')"
          maxlength="100"
          show-password
        />
        <div class="form-tip">{{ t('sop.app.webhookSecretTip') }}</div>
      </el-form-item>

      <el-form-item :label="t('sop.app.tokenExpireHours')" prop="tokenExpireHours">
        <el-input-number
          v-model="formData.tokenExpireHours"
          :placeholder="t('sop.app.rules.tokenExpireHoursRequired')"
          :min="1"
          :max="168"
          style="width: 200px"
        />
        <span class="ml-10px">{{ t('sop.app.hours') }}</span>
        <div class="form-tip">{{ t('sop.app.tokenExpireHoursTip') }}</div>
      </el-form-item>

      <el-form-item :label="t('sop.common.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('sop.common.pleaseInput') + t('sop.common.remark')"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('sop.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('sop.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { getAppInfoApi, createAppInfoApi, updateAppInfoApi } from '@/api/sop/app'
import { getMerchantListApi } from '@/api/settle/merchant'
import type { AppVO, AppCreateReqVO, AppUpdateReqVO, MerchantVO } from '@/api/sop/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'AppForm' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formType = ref('')
const formData = ref<AppCreateReqVO>({
  appName: '',
  merchantNo: '',
  rateLimitPerSecond: 10,
  rateLimitPerMinute: 600,
  ipWhitelist: '',
  notifyUrl: '',
  webhookSecret: '',
  tokenExpireHours: 24,
  remark: ''
})

// 商户选项
const merchantOptions = ref<MerchantVO[]>([])
const merchantLoading = ref(false)

// 表单校验规则
const formRules = reactive<FormRules>({
  appName: [{ required: true, message: t('sop.app.rules.appNameRequired'), trigger: 'blur' }],
  merchantNo: [
    { required: true, message: t('sop.app.rules.merchantNoRequired'), trigger: 'change' }
  ],
  rateLimitPerSecond: [
    { required: true, message: t('sop.app.rules.rateLimitPerSecondRequired'), trigger: 'blur' }
  ],
  rateLimitPerMinute: [
    { required: true, message: t('sop.app.rules.rateLimitPerMinuteRequired'), trigger: 'blur' }
  ],
  ipWhitelist: [
    {
      validator: (rule, value, callback) => {
        if (value && value.trim()) {
          const ips = value
            .split(/[,，\n]/)
            .map((ip) => ip.trim())
            .filter((ip) => ip)
          const ipRegex = /^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$|^\*$/
          for (const ip of ips) {
            if (!ipRegex.test(ip)) {
              callback(new Error(t('sop.app.rules.ipWhitelistFormat')))
              return
            }
          }
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  notifyUrl: [
    {
      type: 'url',
      message: t('sop.app.rules.notifyUrlFormat'),
      trigger: 'blur'
    }
  ],
  tokenExpireHours: [
    { required: true, message: t('sop.app.rules.tokenExpireHoursRequired'), trigger: 'blur' }
  ]
})

// 计算属性
const isUpdate = computed(() => formType.value === 'update')

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开弹窗
 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value =
    type === 'create'
      ? t('sop.common.add') + t('sop.app.title')
      : t('sop.common.edit') + t('sop.app.title')
  formType.value = type
  resetForm()

  // 加载商户列表
  await loadMerchants()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getAppInfoApi(id)
      Object.assign(formData.value, data)
    } catch (error) {
      console.error('获取应用详情失败:', error)
    } finally {
      formLoading.value = false
    }
  }
}

/**
 * 提交表单
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  formLoading.value = true
  try {
    const data = { ...formData.value }
    if (isUpdate.value) {
      await updateAppInfoApi(data as AppUpdateReqVO)
      ElMessage.success(t('sop.app.tips.updateSuccess'))
    } else {
      await createAppInfoApi(data)
      ElMessage.success(t('sop.app.tips.createSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存应用失败:', error)
  } finally {
    formLoading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    appName: '',
    merchantNo: '',
    rateLimitPerSecond: 10,
    rateLimitPerMinute: 600,
    ipWhitelist: '',
    notifyUrl: '',
    webhookSecret: '',
    tokenExpireHours: 24,
    remark: ''
  }
  formRef.value?.resetFields()
}

/**
 * 加载商户列表
 */
const loadMerchants = async () => {
  try {
    merchantLoading.value = true
    const data = await getMerchantListApi(1) // 只获取审核通过的商户
    merchantOptions.value = data
  } catch (error) {
    console.error('加载商户列表失败:', error)
  } finally {
    merchantLoading.value = false
  }
}

/**
 * 搜索商户
 */
const searchMerchants = async (query: string) => {
  if (query) {
    // 这里可以实现远程搜索逻辑
    await loadMerchants()
  }
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.ml-10px {
  margin-left: 10px;
}
</style>
